﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class Departments : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "DepartmentIdSource.Name";
                expression.SetSortOrder("Ascending");
                this.DeparmentsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Departamentos...');", true);
        }

        protected void DeparmentsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetDepartmentsByCompanies(getSessionManager().CompanyIDSelectedComboBox);
            DeparmentsGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
        }

        private void GetDepartmentsByCompanies(int companyID)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.CompaniesByDepartments> CompaniesByDepartmentsEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.GetByCompanyId(companyID);
            GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.DeepLoad(CompaniesByDepartmentsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.Departments));
            DeparmentsGrid.DataSource = CompaniesByDepartmentsEntity;
        }

        private GPSTrackingDBV2.Entities.Departments Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.Departments DepartmentEntity = new GPSTrackingDBV2.Entities.Departments();
            DepartmentEntity.DepartmentId = Convert.ToInt32(Entity[GPSTrackingDBV2.Entities.DepartmentsColumn.DepartmentId.ToString()]);
            DepartmentEntity.Name = Entity["DepartmentIdSource.Name"].ToString();

            return DepartmentEntity;
        }

        protected void DeparmentsGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);
                
                Entity["DepartmentId"] = GPSTrackingDBV2Custom.Data.DataRepository.DepartmentsProvider.GetNextID();

                GPSTrackingDBV2.Entities.Departments DepartmentEntity = Invoke_Entity(Entity);
                //DepartmentEntity.DepartmentId = 

                GPSTrackingDBV2.Data.DataRepository.DepartmentsProvider.Insert(tm, DepartmentEntity);

                GPSTrackingDBV2.Entities.CompaniesByDepartments CompaniesByDepartmentsEntity = new GPSTrackingDBV2.Entities.CompaniesByDepartments();

                CompaniesByDepartmentsEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                CompaniesByDepartmentsEntity.DepartmentId = DepartmentEntity.DepartmentId;

                GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.Insert(tm, CompaniesByDepartmentsEntity);

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);        
                showErrorMessage("No se puede registrar el departamento.");
            }  
        }

        protected void DeparmentsGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Departments DepartmentEntity = Invoke_Entity(Entity);
                DepartmentEntity.OriginalDepartmentId = DepartmentEntity.DepartmentId;

                GPSTrackingDBV2.Data.DataRepository.DepartmentsProvider.Update(tm, DepartmentEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);        
                showErrorMessage("No se puede actualizar el departamento.");
            } 

        }

        protected void DeparmentsGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Departments DepartmentEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.Delete(tm, getSessionManager().CompanyIDSelectedComboBox, DepartmentEntity.DepartmentId);

                GPSTrackingDBV2.Data.DataRepository.DepartmentsProvider.Delete(tm, DepartmentEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);        
                if (ex.Message.Contains("FK_AdministratorsByCompaniesByDepartments"))
                    showErrorMessage("No se puede eliminar el departamento porque esta asociado a usuarios Administradores, debe quitar la asociación y luego volver a proceder con la eliminación.");                    
                else
                    showErrorMessage("No se puede eliminar el departamento porque esta asociado a otros registros.");                    
            } 
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            DeparmentsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in DeparmentsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            DeparmentsGrid.MasterTableView.Rebind();
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }
    }
}